/**
 * 
 */
package com.snsoft.service.duty;

import java.sql.SQLException;
import java.util.List;

import com.snsoft.bean.User;
import com.snsoft.bean.UserInfo;
import com.snsoft.dao.DutyDao;
import com.snsoft.dao.UserDao;
import com.snsoft.exception.PromiseRefused;
import com.snsoft.exception.RepetOperate;
import com.snsoft.exception.UserExist;

/**
 * @author 苏国启
 * 
 * @date 2017年11月21日 下午1:28:27
 * 
 * @Description TODO
 * 
 *              设置温室控制权限接口业务逻辑
 * 
 */
public class SetOperateService {

	/**
	 * 设置温室控制权限
	 * 
	 * @param userID
	 * @param operate
	 * @throws RepetOperate
	 * @throws UserExist
	 * @throws SQLException
	 * @throws NumberFormatException
	 * @throws PromiseRefused
	 */
	public void setOperate(String userID, String operate, UserInfo admin)
			throws RepetOperate, UserExist, NumberFormatException, SQLException, PromiseRefused {
		User user = new UserDao().getUser(Integer.parseInt(userID));
		DutyDao dd = new DutyDao();
		if (user == null) {
			throw new UserExist("目标用户不存在！");
		}
		if (user.getRole() == 1) {
			throw new PromiseRefused("无法为管理员设置温室控制权限！");
		}
		if (admin.getRole() == 2) {
			List<Integer> companyids = dd.getUserCompanyIds(admin.getUserID());
			List<Integer> usercompany = dd.getUserCompanyIds(Integer.parseInt(userID));
			if (user.getRole() == 2 || companyids.isEmpty() || usercompany.isEmpty()
					|| !companyids.contains(usercompany.get(0))) {
				throw new PromiseRefused("您无权为该用户设置温室控制权限！");
			}
		}
		if (operate.equals(user.getOperate() + "")) {
			throw new RepetOperate("用户权限已设置为" + (operate.equals("1") ? "可控制" : "不可控制") + "，无需重复设置！");
		}
		dd.setOperate(userID, operate);
	}

}
